<script setup lang="ts">
import { useColumns } from "./columns";
import { Plus } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import AdvertisementInfo from "./AdvertisementInfo.vue";
import {
  getAdvertisementList,
  getAdvertisementDetail
} from "@/api/advertisement";
import { getExhibitorId } from "@/utils/getExhibitorId";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "advertisementInfo"
});

// 表格数据
const advertisementList = ref([]);
const loading = ref(false);

// 分页信息
const pagination = ref({
  total: 0,
  page: 1,
  limit: 10
});

onMounted(() => {
  getAdvertisementListData();
});

// 获取广告列表
const getAdvertisementListData = async (page = 1, limit = 10) => {
  try {
    loading.value = true;
    const exhibitor_id = getExhibitorId();
    const res: any = await getAdvertisementList(page, limit, exhibitor_id);
    console.log("API返回的完整数据:", res);
    console.log("列表数据:", res.data.list);
    // 将API数据赋值给表格
    advertisementList.value = res.data.list || [];
    // 更新分页信息
    pagination.value = {
      total: res.data.total,
      page: res.data.page,
      limit: res.data.limit
    };
    console.log("赋值后的表格数据:", advertisementList.value);
  } catch (error) {
    console.error("获取广告列表失败:", error);
    advertisementList.value = [];
  } finally {
    loading.value = false;
  }
};

// 分页改变
const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  getAdvertisementListData(page, 10);
};

const handleRefresh = () => {
  // 调用列表查询接口
  console.log("刷新");
  getAdvertisementListData(pagination.value.page, 10);
};

const handleAdd = () => {
  // 处理新增逻辑，使用 @components已封装好的组件
  console.log("新增数据");
  formMode.value = "add";
  currentFormData.value = null; // 新增时清空数据
  isShowEditDialog.value = true;
};

const handleView = async (row: any) => {
  // 处理查看逻辑
  console.log("查看数据", row);
  try {
    const exhibitor_id = getExhibitorId();
    const result: any = await getAdvertisementDetail(row.id, exhibitor_id);
    if (result.code === 1) {
      currentFormData.value = { ...result.data, mode: "view" };
      formMode.value = "view";
      isShowEditDialog.value = true;
    } else {
      ElMessage.error(result.msg || "获取广告详情失败");
    }
  } catch (error) {
    console.error("获取广告详情失败:", error);
    ElMessage.error("获取广告详情失败，请重试");
  }
};

const handleEdit = async (row: any) => {
  // 处理修改逻辑
  console.log("修改数据", row);
  try {
    const exhibitor_id = getExhibitorId();
    const result: any = await getAdvertisementDetail(row.id, exhibitor_id);
    if (result.code === 1) {
      currentFormData.value = { ...result.data, mode: "edit" };
      formMode.value = "edit";
      isShowEditDialog.value = true;
    } else {
      ElMessage.error(result.msg || "获取广告详情失败");
    }
  } catch (error) {
    console.error("获取广告详情失败:", error);
    ElMessage.error("获取广告详情失败，请重试");
  }
};

const { tableData, columns } = useColumns(
  advertisementList,
  handleView,
  handleEdit,
  handleRefresh
);

// 用于强制重建子组件，清空其内部状态（如图片预览）
const adDialogKey = ref(0);

const resetDialogState = () => {
  // 重置父级保存的数据
  currentFormData.value = null;
  formMode.value = "add";
  // 通过更换 key 强制子组件重新挂载，从而清空 imagePreview 等内部状态
  adDialogKey.value++;
};

const handleCancel = () => {
  isShowEditDialog.value = false;
  resetDialogState();
};

const handleDialogClose = () => {
  // 处理点击关闭、遮罩关闭等情况
  resetDialogState();
};

const handleConfirm = (formData: any) => {
  // 处理确认逻辑
  console.log("确认提交", formData);
  isShowEditDialog.value = false;
  // 刷新列表
  getAdvertisementListData(pagination.value.page, 10);
};

const isShowEditDialog = ref(false);
const currentFormData = ref(null); // 当前表单数据
const formMode = ref<"add" | "view" | "edit">("add"); // 表单模式
</script>

<template>
  <div>
    <!-- 统一的白色背景容器 -->
    <div class="table-container">
      <!-- 自定义头部 -->
      <div class="custom-header">
        <div class="header-left">
          <h2 class="header-title">广告上传</h2>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            提交广告
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <pure-table :data="tableData" :columns="columns" :loading="loading" />

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          :page-size="10"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 弹框放在最外层，避免被其他组件影响 -->

    <el-dialog v-model="isShowEditDialog" @close="handleDialogClose">
      <AdvertisementInfo
        :key="adDialogKey"
        :mode="formMode"
        :initial-data="currentFormData"
        @cancel="handleCancel"
        @confirm="handleConfirm"
      />
    </el-dialog>
  </div>
</template>

<style scoped>
/* 统一的白色背景容器 */
.table-container {
  background-color: #fff;
  padding: 0 20px;
}

/* 自定义头部样式 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left .header-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 分页容器样式 */
.pagination-container {
  padding: 20px 0;
  text-align: center;
  display: flex;
  justify-content: center;
  width: 100%;
}
</style>
